package net.mingsoft.basic.action.web;


import agw.service.gm.client.GMServiceClient;
import agw.service.gm.client.GMServiceStub;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.util.AGWUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@Api("USBKEY")
@RestController
@RequestMapping("/usb")
@Slf4j
public class RandomCodeAction {
    @Data
    static class ValiDateParams {
        private String userSignCertB64;
    }

    @ApiOperation("获取随机码")
    @GetMapping(value = "/code")
    @ResponseBody
    public ResultData validateCertGenRandom(@RequestParam String userSignCertB64) {
        GMServiceClient client = AGWUtils.getClient();
        GMServiceStub.CkCertReq ckCertReq = new GMServiceStub.CkCertReq();
        ckCertReq.setAppID(AGWUtils.getAppid());
        ckCertReq.setOperID(AGWUtils.CERT_CHECK);
        ckCertReq.setCert(userSignCertB64);
        log.info("tdg|AgwServiceImpl|validateCertGenRandom|req={}", JSONObject.toJSON(ckCertReq));
        GMServiceStub.CkCertResp ckCertResp = client.validateCert(ckCertReq);
        log.info("tdg|AgwServiceImpl|validateCertGenRandom|resp={}", JSONObject.toJSON(ckCertResp));
        if (ckCertResp == null) {
            throw new RuntimeException("验证签名失败，签名结果返回为空");
        }
        if (ckCertResp.getResult() != 0) {
            String sException = "";
            if (ckCertResp.getResult() == 0x0100) {
                sException = "certificate chain valid fail" + ckCertResp.getResult();
            }
            if (ckCertResp.getResult() == 0x0101) {
                sException = "OCSP valid fail:" + ckCertResp.getResult();
            }
            if (ckCertResp.getResult() == 0x0102) {
                sException = "certificate application valid fail:" + ckCertResp.getResult();
            }
            if (ckCertResp.getResult() == 0x0104) {
                sException = "certificate has been revoked:" + ckCertResp.getResult();
            } else {
                sException = "check cert valid fail,result:" + ckCertResp.getResult();
            }
            throw new RuntimeException("验证签名失败，结果：" + sException);
        }
        String randomData = client.genRandom((short) 24);
        if (randomData.length() < 24) {
            throw new RuntimeException("获取随机数失败，请稍后再试");
        }
        return ResultData.build().success(randomData);
    }
}
